package com.jackrain.nea.omslocal.Dao;

import com.alibaba.dubbo.common.utils.Log;
import com.alibaba.dubbo.common.utils.NetUtils;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.parser.Feature;
import com.alibaba.fastjson.util.TypeUtils;
import com.jackrain.nea.config.PropertiesConf;
import com.jackrain.nea.omslocal.service.LocalLogService;
import com.jackrain.nea.omslocal.service.SendMqServies;
import com.jackrain.nea.omslocal.util.JsonKeyCheck;
import com.jackrain.nea.omslocal.util.RegexDateUtil;
import com.jackrain.nea.util.ApplicationContextHandle;
import com.jackrain.nea.util.Tools;
import com.jackrain.nea.util.Validator;
import com.jackrain.nea.web.query.QueryEngine;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.ArrayUtils;
import org.apache.commons.lang3.time.FastDateFormat;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import java.io.PrintWriter;
import java.io.StringWriter;
import java.sql.SQLException;
import java.text.ParseException;
import java.util.Date;
import java.util.Set;

/**
 * @Discription: 线下消费淘宝换货数据
 * Created with IntelliJ IDEA.
 * @Author cs
 * @Date 2017/12/19 11:10
 */
@Component
@Slf4j
public class TaoBaoEXChangeDao {

    @Autowired
    private RegexDateUtil regexDate;
    @Autowired
    private LocalLogService localLogService;
    private FastDateFormat fastformat = FastDateFormat.getInstance("yyyy-MM-dd HH:mm:ss");
    @Autowired
    private SendMqServies sendMq;

    /**
     * 保存淘宝换货数据
     * @param exchangeObj
     * @param topic
     * @param msgkey
     */
    public void exchangeStart(JSONObject exchangeObj, String msgkey, String topic) throws Exception {

        TaoBaoEXChangeDao taoBaoEXChangeDao = ApplicationContextHandle.getBean(TaoBaoEXChangeDao.class);
        PropertiesConf pconf = (PropertiesConf) ApplicationContextHandle.getBean("propertiesConf");

        int countFaild = 0;
        // 定义接收消费日志信息的 jsonobject
        JSONObject infoObj = new JSONObject();

        JSONObject jsonObject1 = exchangeObj.getJSONObject("tmall_exchange_receive_get_response");
        JSONObject jsonObject2 = jsonObject1.getJSONObject("results");
        JSONArray exchangeArray = jsonObject2.getJSONArray("exchange");

        if (jsonObject1.getInteger("total_results") == 0) {
            // 没有数据
            log.debug("换货单数据为空 " + msgkey);
            return;
        }
        // 没有明细表,直接新增主表或更新主表
        for (Object obj : exchangeArray) {

            JSONObject tempObj = null;
            try {
                // 循环遍历获取换货数据
                tempObj = JSONObject.parseObject(obj.toString(), Feature.OrderedField);
                Long dispute_id = tempObj.getLong("dispute_id");
                // 判断该数据是 新增 或是 修改
                String selectSql = "SELECT id FROM T_OMSTAOBAOEXCHANGE WHERE dispute_id = ?";
                int id = Tools.getInt(QueryEngine.getInstance().doQueryOne(selectSql, new Object[]{dispute_id}), -1);
                if (id < 0) {
                    // 数据不为空 保存数据
                    taoBaoEXChangeDao.saveExchangeOrder(tempObj);
                    localLogService.insertLogDeatail(tempObj, dispute_id, 1, topic, msgkey);

                } else {
                    boolean flag = checkStatus(id, tempObj);
                    if (flag){
                        // 根据查询到的 id 更新主表数据
                        taoBaoEXChangeDao.updateExchangeOrder(tempObj, id);
                        localLogService.insertLogDeatail(tempObj, dispute_id, 2, topic, msgkey);
                    }
                    continue;

                }
            } catch (Exception e) {
                StringWriter sw = new StringWriter();
                PrintWriter pw = new PrintWriter(sw);
                // 逐条将错误信息以消息发送到线上发送到线上
                JSONObject errObj = new JSONObject();
                errObj.put("tablename", pconf.getProperty("ons.tbrefund"));
                errObj.put("topic", topic);
                errObj.put("tag", pconf.getProperty("ons.comp"));
                errObj.put("msgkey", msgkey);
                // 线下消费报错的主机 ip
                errObj.put("client_ip", NetUtils.getLocalAddress());
                errObj.put("code", -1);
                // 将错误以流写出
                e.printStackTrace(pw);
                errObj.put("errmsg", sw.toString());
                errObj.put("protime", System.currentTimeMillis());
                sendMq.sendMqinfoObj(errObj, pconf.getProperty("ons.loginfor.err.topic"), pconf.getProperty("ons.loginfor.err.tag"));
                countFaild++;
                localLogService.insertLog(e.getMessage(), tempObj, tempObj.getLong("dispute_id"), topic, msgkey);
            }

        }
        // 消费回执
        infoObj.put("msgkey", msgkey);
        infoObj.put("client_ip", NetUtils.getLocalAddress());
        infoObj.put("topic", topic);
        infoObj.put("countsuccess", (exchangeArray.size() - countFaild));
        infoObj.put("protime", System.currentTimeMillis());
        infoObj.put("code", 0);
        infoObj.put("total", exchangeArray.size());
        sendMq.sendMqinfoObj(infoObj, pconf.getProperty("ons.loginfor.suf.topic"), pconf.getProperty("ons.loginfor.suf.tag"));

    }

    /**
     * 保存换货单主表
     * @param jsonObj
     * @return
     * @throws SQLException
     */
    @Transactional
    public void saveExchangeOrder(JSONObject jsonObj) throws SQLException, ParseException {

        JsonKeyCheck checkjson = ApplicationContextHandle.getBean(JsonKeyCheck.class);
        jsonObj = checkjson.checkJsonkeycache(jsonObj, "T_OMSTAOBAOEXCHANGE", checkjson.getInsertcolsmap());
        // 获取主表的 sequences
        String squnceSql = "select get_wsequences('T_OMSTAOBAOEXCHANGE') as SEQ from dual";
        Long id = TypeUtils.castToLong(QueryEngine.getInstance().doQueryOne(squnceSql));

        jsonObj.put("id", id);
        String columnName = "";
        String columnValue = "";
        Set set = jsonObj.keySet();
        Object[] objArr = jsonObj.values().toArray();

        for (Object obj1 : set) {
            columnName = columnName + "," + obj1;
        }
        columnName = columnName.substring(1);

        for (int i = 0; i < objArr.length; i++) {

            if (objArr[i] instanceof String) {
                if (regexDate.regexDate(((String) objArr[i]))) {
                    Date date = fastformat.parse(((String) objArr[i]));
                    objArr[i] = date;
                }
            }
            columnValue = columnValue + ",?";
        }

        columnValue = columnValue.substring(1);
        String sql = "insert into T_OMSTAOBAOEXCHANGE (" + columnName + ") values (" + columnValue + ")";
        int code = QueryEngine.getInstance().executeUpdate(sql, objArr);

    }

    /**
     * 更新换货单主表
     * @param jsonObj
     * @return
     * @throws SQLException
     */

    @Transactional
    public void updateExchangeOrder(JSONObject jsonObj, int id) throws SQLException, ParseException {
        JsonKeyCheck checkjson = ApplicationContextHandle.getBean(JsonKeyCheck.class);
        jsonObj = checkjson.checkJsonkeycache(jsonObj, "T_OMSTAOBAOEXCHANGE", checkjson.getUpdatecolsmap());
        log.debug(jsonObj.toString());
        jsonObj.put("istrans",0);
        String params = "";
        Set set = jsonObj.keySet();
        Object[] objArr = jsonObj.values().toArray();
        for (Object obj1 : set) {
            Object tempobject = jsonObj.get(obj1);
            params = params + "" + obj1 + " = ?,";
        }
        params = params.substring(0, params.length() - 1);

        for (int i = 0; i < objArr.length; i++) {

            if (Validator.isNull(objArr[i])) {
                objArr[i] = "null";
            }
            if (objArr[i] instanceof String) {
                if (regexDate.regexDate(((String) objArr[i]))) {
                    Date date2 = fastformat.parse(((String) objArr[i]));
                    objArr[i] = date2;
                }
            }
        }

        String sql = "update t_omstaobaoexchange set " + params + " where id = ?";
        log.debug("======================" + jsonObj.toString());
        int code = QueryEngine.getInstance().executeUpdate(sql, ArrayUtils.add(objArr, id));

    }

    /**
     * 校验换货单修改时间，避免覆盖状态
     * @param id
     */
    private boolean checkStatus(int id ,JSONObject jsonObject){
        boolean flag = true;

        try {
            // 查询数据库中换货单修改时间，与当前数据中的修改时间
            String selSql = "select modified from t_omstaobaoexchange where id = ?";
            Date dbDate = (Date) QueryEngine.getInstance().doQueryOne(selSql,new Object[]{id});
            if (dbDate == null ){
               // 没有修改时间，默认修改
                return flag;
            }
            Long dbTim = dbDate.getTime();
            Long dateTime = jsonObject.getDate("modified").getTime();

            if (dbTim > dateTime){
                flag =false;
            }
        } catch (Exception e) {
            log.error(" 判断换货单是否能修改出现异常 ： "+   e.getCause().getMessage());
            return flag;
        }

        return  flag;
    }


}
